<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    :title="title"
    width="900px"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="60px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12"
          ><el-form-item label="标题" prop="videoName">
            <el-input
              v-model="formData.videoName"
              :disabled="isDisabled"
              show-word-limit
              maxlength="20"
            /> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="类型" prop="videoTypeIds">
            <el-select
              :disabled="isDisabled"
              v-model="formData.videoTypeIds"
              multiple
              style="width: 100%"
            >
              <el-option
                :value="item.id"
                :label="item.typeName"
                v-for="item in videoTypeList"
                :disabled="item.state != 1"
                :key="item.id"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="视频" prop="videoFileUrl">
            <el-upload
              ref="upload"
              class="upload-demo"
              :on-success="(response: any) => onUploadSuccess(response, 1)"
              :on-progress="onProgress"
              :before-upload="beforeAvatarUpload"
              :auto-upload="true"
              :show-file-list="false"
              :headers="{ [`x-auth-token`]: xAuthToken }"
              :action="`${baseURL}manage/v1/storage/uploadMp4?dir=videoDir`"
            >
              <template #trigger>
                <el-button
                  :loading="btnLoading"
                  :disabled="isDisabled"
                  type="primary"
                  >上传视频</el-button
                >
              </template>
            </el-upload>
            <!-- <div class="videoWrap"> -->
            <video-player
              class="videoWrap"
              v-if="formData.videoFileUrl"
              :src="baseURL + formData.videoFileUrl"
              :options="playerOptions"
              :volume="1.0"
              style="margin-top: 5px"
            />
            <!-- </div> -->
            <!--        <video
            v-if="formData.videoFileUrl"
            style="width: 300px; height: 150px; margin: 10px"
            :src="baseURL + formData.videoFileUrl"
          ></video>-->
          </el-form-item></el-col
        >
        <el-col :span="12">
          <el-form-item
            label="封面"
            prop="infoFileUrl"
          >
            <el-upload
              style="width: 100%"
              ref="uploadRef"
              class="avatar-uploader"
              :headers="{ 'x-auth-token': xAuthToken }"
              :show-file-list="false"
              :before-upload="beforeAvatarUploadImg"
              :action="`${baseURL}manage/v1/storage/upload?dir=videoDir`"
              :on-success="(response: any) => onUploadSuccess(response, 2)"
            >
              <template #trigger>
                <el-button
                  :loading="btnLoading"
                  :disabled="isDisabled"
                  type="primary"
                  >更换封面</el-button
                >
              </template>
            </el-upload>

            <div>
              <el-image

                  v-if="formData.imageFileUrl"
                :src="baseURL + formData.imageFileUrl"
                class="avatar"
                style="height: 210px; margin-top: 5px;border:1px solid #999"
              />
            </div> </el-form-item
        ></el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <el-button
        v-if="!isDisabled"
        @click="submitForm(ruleFormRef)"
        type="primary"
        :loading="submitLoading"
      >
        保存
      </el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules, UploadProps } from "element-plus";
import { baseURL } from "@/util/request";
import { ApiResult } from "@/util/request";
import { addVideo, selectVideoList, updateVideo } from "@/api/videoManage.ts";

interface IForm {
  id: string;
  videoName: string;
  videoFileUrl: string;
  imageFileUrl: string;
  imageFileId: string;
  videoFileId: string;
  videoTypeIds: [];
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
  isDisabled: {
    type: Boolean,
    default: false,
  },
  parentMenuOption: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "update:data", "submit"]);

const ruleFormRef = ref();
const uploadRef = ref();
const videoTypeList = ref<any[]>([]);
const submitLoading = ref<boolean>(false);
const xAuthToken = ref<string>(localStorage.getItem("x-auth-token"));

const formData = reactive<IForm>({
  id: "",
  videoName: "",
  videoFileUrl: "",
  videoFileId: "",
  imageFileUrl: "",
  imageFileId: "",
  videoTypeIds: [],
});

let btnLoading = ref<boolean>(false);
let playerOptions = ref({
  // height: 200,
  // width: document.documentElement.clientWidth, //播放器宽度
  playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
  autoplay: false, // 如果true,浏览器准备好时开始回放。
  muted: true, // 默认情况下将会消除任何音频。
  loop: true, // 导致视频一结束就重新开始。
  preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
  language: "zh-CN",
  aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
  fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
  notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
  controls: true,
  controlBar: {
    timeDivider: true,
    durationDisplay: true,
    remainingTimeDisplay: false,
    fullscreenToggle: true, // 全屏按钮
  },
});

//TODO 做成动态
const rules = reactive<FormRules<IForm>>({
  videoName: [{ required: true, message: "请输入", trigger: "blur" }],
  videoFileUrl: [{ required: true, message: "请上传", trigger: "change" }],
  videoTypeIds: [{ required: true, message: "请选择", trigger: "change" }],
});

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

//TODO 做成动态
const title = computed(() => {
  return props?.data?.id ? (props?.isDisabled ? "详情" : "编辑") : "新增";
});

function clearUploadFile() {
  uploadRef.value?.clearFiles();
}

function onUploadSuccess(response: any, sign: any) {
  if (response?.code === 500) {
    ElMessage.error(response?.msg || "上传错误！");
    clearUploadFile();
    return;
  }
  if (sign == 1) {
    formData.videoFileUrl = response?.data?.fileUrl;
    formData.videoFileId = response?.data?.id;
    formData.imageFileUrl = response?.data?.ImgUrl;
    formData.imageFileId = response?.data?.imgId;
    btnLoading.value = false;
  } else {
    formData.imageFileUrl = response?.data?.fileUrl;
    formData.imageFileId = response?.data?.id;
  }

  ElMessage.success("上传完成！");
}
function onProgress() {
  btnLoading.value = true;
}
function closeDialog() {
  resetForm(ruleFormRef.value);
  emit("update:visible", false);
  emit("update:data", null);
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

async function getSelectVideoList() {
  const { success, msg, data } = await selectVideoList();
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  videoTypeList.value = data;
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>;
    if (valid) {
      submitLoading.value = true;
      if (formData?.id) {
        result = await updateVideo(formData);
      } else {
        result = await addVideo(formData);
      }
      const { success, msg } = result;
      submitLoading.value = false;
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      ElMessage.success("操作成功");
      closeDialog();
      emit("submit");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile);
  if (rawFile.type.split("/")[0] !== "video") {
    ElMessage.error("只能上传视频!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 500) {
    ElMessage.error("视频不能大于500M");
    return false;
  }
  return true;
};
const beforeAvatarUploadImg: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type.split("/")[0] !== "image") {
    ElMessage.error("只能上传图片!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error("图片不能大于1M");
    return false;
  }
  return true;
};

onMounted(async () => {
  await getSelectVideoList();
});
watch(dialogVisible, (visible) => {
  Object.keys(formData).forEach((key: any) => {
    formData[key as keyof IForm] = visible ? props.data?.[key] || "" : "";
  });
});
</script>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
.upload-demo {
  width: 100%;
}
.videoWrap {
  border: 1px solid #999;
}
</style>
